//
//  YWGrabTroubleBillTableViewController.m
//  maintain
//
//  Created by kyo on 16/12/5.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWGrabTroubleBillTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "MJRefresh.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "NSDate+Additions.h"
#import "YWCommonTool.h"

#import "YWGrabTroubleBillCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

#import "YWMission.h"

#import "YWMissionManager.h"
#import "YWEwinManager.h"
#import "YWCirculationDetailViewController.h"
#import "YWWriteGrabTroubleInfoViewController.h"
#import "YWNavigationController.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"
#import "YWBuilding.h"
#import "YWApartment.h"
#import "YWEquipmentType.h"

@interface YWGrabTroubleBillTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,YWGrabTroubleBillCellDelegate>{
    NSInteger page;
}
@property (nonatomic, strong) NSMutableArray *tempDataArray;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation YWGrabTroubleBillTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"grabTroubleBill", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    [self setupNotifications];
    [self setupTableView];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showTipsWhenFirstEnter];
    });
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableViewByNotification:) name:KPostGrabTroubleBillSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableViewByNotification:) name:KPostGrabTroubleBillFailNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableViewByNotification:) name:KPostReportTroubleNoReadCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableViewByNotification:) name:KPostAssignTroubleBillNotification object:nil];
}

- (void)setupTableView{
    page = 1;
    [self.tableView registerClass:[YWGrabTroubleBillCell class] forCellReuseIdentifier:NSStringFromClass([YWGrabTroubleBillCell class])];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)refreshTableViewByNotification:(id)sender{
    [self refreshTop];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
//        _dataSource = [[NSArray alloc] initWithArray:[[YWReportTroubleManager shareManager] getReportTroubleUnassignBillsWithPage:page]];
    }
    return _dataSource;
}

- (NSMutableArray*)tempDataArray{
    if (!_tempDataArray) {
        _tempDataArray = [NSMutableArray array];
    }
    return _tempDataArray;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return [self.dataSource  count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataSource[section]  count];
}

#pragma mark - UITableViewDelegate mothods
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:NSStringFromClass([YWGrabTroubleBillCell class]) cacheByIndexPath:indexPath configuration:^(YWGrabTroubleBillCell *cell) {
//        cell.reportTrouble = self.dataSource[indexPath.section][indexPath.row];
//        cell.delegate = self;
//    }];
//}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
    YWGrabTroubleBillCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([YWGrabTroubleBillCell class])];
    cell.reportTrouble = self.dataSource[indexPath.section][indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDataDelegate mothods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWCirculationDetailViewController *circulationDetailVC = [[YWCirculationDetailViewController alloc] init];
    YWReportTroubleModel *reportTrouble = self.dataSource[indexPath.section][indexPath.row];
    YWReportTroubleModel * cirReportTrouble = [[YWReportTroubleManager shareManager] getOneReportTroubleWithTroubleId:reportTrouble.troubleId];
    circulationDetailVC.isGrabTroubleBill = YES;
    circulationDetailVC.troubleMissionModel = cirReportTrouble.troubleMission;
    [self.navigationController pushViewController:circulationDetailVC animated:YES];
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}
#pragma mark - YWGrabTroubleBillCellDelegate
- (void)clickGrabBillEvent:(UITableViewCell *)cell{
    YWWriteGrabTroubleInfoViewController *grabTroubleBillVC = [[YWWriteGrabTroubleInfoViewController alloc] init];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YWReportTroubleModel * reportTrouble = self.dataSource[indexPath.section][indexPath.row];
    grabTroubleBillVC.reportTroubleModel = reportTrouble;
    YWNavigationController* nav = [[YWNavigationController alloc] initWithRootViewController:grabTroubleBillVC];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWGrabTroubleBillTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *temp = self.dataSource[section];
    YWReportTroubleModel* troubleMission = temp.count ? temp[0] : nil;
    NSString *time = [YWCommonTool showChineseFormatterDate:troubleMission.reportTime/1000];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:troubleMission.reportTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}

- (void)refreshTop
{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
//    dispatch_group_t group = dispatch_group_create();
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (refreshType == YWTableViewFreshTypeUp) {
            page++;
        }
//        dispatch_group_enter(group);
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        NSDictionary * saveDic = [NSKeyedUnarchiver unarchiveObjectWithFile:[self savefilePath:KYWRememberSelectSubscriptionKey]];
        NSMutableArray * selLocArray = [NSMutableArray array];
        NSMutableArray * systemTypeArray = [NSMutableArray array];
        selLocArray = [saveDic objectForKey:@"selLocArray"];
        systemTypeArray = [saveDic objectForKey:@"systemTypeArray"];
        NSMutableArray * buildingArray = [NSMutableArray array];
        NSMutableArray * apartmentArray = [NSMutableArray array];
        for (id obj in selLocArray) {
            if ([obj isKindOfClass:[YWBuilding class]]) {
                YWBuilding * building = (YWBuilding*)obj;
                [buildingArray addObject:building];
            }else if ([obj isKindOfClass:[YWApartment class]]){
                YWApartment *apartment = (YWApartment*)obj;
                [apartmentArray addObject:apartment];
            }
        }
        NSMutableString *buildingIds = [[NSMutableString alloc] init];
        [buildingArray enumerateObjectsUsingBlock:^(YWBuilding*  _Nonnull building, NSUInteger idx, BOOL * _Nonnull stop) {
            if (building.buildingId.length && idx!=0) {
                [buildingIds appendString:@","];
            }
            [buildingIds appendString:building.buildingId];
        }];
        
        NSMutableString *apartmentIds = [[NSMutableString alloc] init];
        [apartmentArray enumerateObjectsUsingBlock:^(YWApartment*  _Nonnull apartment, NSUInteger idx, BOOL * _Nonnull stop) {
            if (apartment.apartmentId != 0 && idx!=0) {
                [apartmentIds appendString:@","];
            }
            [apartmentIds appendString:[@(apartment.apartmentId) stringValue]];
        }];
        NSMutableString *systemTypeIds = [[NSMutableString alloc] init];
        [systemTypeArray enumerateObjectsUsingBlock:^(YWEquipmentSystemType*  _Nonnull systemType, NSUInteger idx, BOOL * _Nonnull stop) {
            if (systemType.systemTypeId != 0 && idx!=0) {
                [systemTypeIds appendString:@","];
            }
            [systemTypeIds appendString:[@(systemType.systemTypeId) stringValue]];
        }];
        if (buildingIds.length>0) {
            [params setValue:buildingIds?: @"" forKey:@"buildingIds"];
        }
        if (apartmentIds.length>0) {
            [params setValue:apartmentIds?: @"" forKey:@"apartmentIds"];
        }
        if (systemTypeIds.length>0) {
            [params setValue:systemTypeIds?: @"" forKey:@"systemTypeIds"];
        }
        [params setValue:@(page) forKey:@"page"];
        [params setValue:@(10) forKey:@"pageSize"];
        [params setValue:@(YWTroubleMissionStatusUnAssign) forKey:@"troubleStatus"];
        [[YWReportTroubleManager shareManager] requestReportTroubleWithDictionary:params completeBlock:^(NSArray *reportTroubleArray) {
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tempDataArray removeAllObjects];
            }else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            [weakSelf.tempDataArray addObjectsFromArray:reportTroubleArray];
            [weakSelf.dataSource removeAllObjects];
            //按照时间构建二维数组
            __block NSString *lastDate = nil;
            __block NSMutableArray *array = nil;
            __block NSMutableArray * troubleArray = [NSMutableArray array];
            [weakSelf.tempDataArray enumerateObjectsUsingBlock:^(YWReportTroubleModel * _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *timeDate = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
                if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                    lastDate = timeDate;
                    array = [NSMutableArray array];
                }
                [array addObject:reportTrouble];
                if (![troubleArray containsObject:array] && array.count) {
                    [troubleArray addObject:array];
                }
            }];
            
            [weakSelf.dataSource addObjectsFromArray:troubleArray];
            [weakSelf.tableView reloadData];
//            dispatch_group_leave(group);
        }];
        
//        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (refreshType == YWTableViewFreshTypeDown) {
//                [weakSelf.tableView.mj_header endRefreshing];
//            }
//            else {
//                [weakSelf.tableView.mj_footer endRefreshing];
//            }
//            weakSelf.dataSource = nil;
//            [weakSelf.tableView reloadData];
//        });
    });
}

- (NSString*)savefilePath:(NSString*)fileName
{
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
    return filePath;
}

#pragma mark - alert view
- (void)showTipsWhenFirstEnter{
    BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:KNotFirstEnterGrabTroubleBill] boolValue];
    if (!notFirstEnter) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(KFirstEnterGrabTroubleBillTips, nil) preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"dontPromptAgain", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNotFirstEnterGrabTroubleBill];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
